package com.ctsi.commons.util;

/**
 * 简单log类
 * 
 * @author yueming
 * 
 */
public class Log {
	public static final CallDetective detective = new CallDetective();

	private int callLevel = 1;

	public Log() {
		super();
	}

	private static final Log log = new Log(2);

	/**
	 * 代替system.out
	 * 
	 * @param msg
	 */
	public static void logInfo(Object msg) {
		log.log(msg);
	}

	public Log(int level) {
		super();
		callLevel = level;
	}

	public void log(String msg) {
		String source = detective.findCaller(callLevel);
		System.out.println(source + " : " + msg);
	}

	public void log(Object msg) {
		String source = detective.findCaller(callLevel);
		if (msg != null) {

			System.out.println(source + " : " + msg);
		} else {
			System.out.println(source + " : null");
		}

	}

	public static String getCallMethod() {
		return detective.findCallerMethiod(1);
	}

	public static String getCallClass() {
		return detective.findCallerClassName(1);
	}

	public int getCallLevel() {
		return callLevel;
	}

	public void setCallLevel(int callLevel) {
		this.callLevel = callLevel;
	}

	public static class CallDetective {
		private final Throwable tracer = new Throwable();

		public String findCaller(int depth) {
			if (depth < 0) {
				throw new IllegalArgumentException();
			}
			tracer.fillInStackTrace();
			return tracer.getStackTrace()[depth + 1].toString();
		}

		public String findCallerClassName(int depth) {
			if (depth < 0) {
				throw new IllegalArgumentException();
			}
			tracer.fillInStackTrace();
			return tracer.getStackTrace()[depth + 1].getClassName();
		}

		public String findCallerMethiod(int depth) {
			if (depth < 0) {
				throw new IllegalArgumentException();
			}
			tracer.fillInStackTrace();
			return tracer.getStackTrace()[depth + 1].getMethodName();
		}

		public boolean containsClass(String className) {

			tracer.fillInStackTrace();
			StackTraceElement[] ses = tracer.getStackTrace();
			for (StackTraceElement se : ses) {
				if (se.getClassName().equals(className))
					return true;
			}
			return false;
		}
	}
}
